/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.mapbar.pay.util;

import com.mapbar.pay.entity.User;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;

/**
 *公用类
 * @author fengbj
 */
public class Util {

    public static Logger logger = Logger.getLogger(Util.class);//getLogger(this.getClass());
    /**
     * 接口配置文件
     */
    private static Properties urlPros;

    /**
     * 给参数解码
     */
    public static String encode(String s) {

        if (s != null) {
            if (s.indexOf("%") >= 0) {
                try {
                    s = URLDecoder.decode(s, ProjectUtil.ENCODE);
                } catch (UnsupportedEncodingException ex) {
                    logger.error("URLDecoder异常:input = " + s + "; ex = " + ex.toString());
                }

            } else {
                try {
                    s = new String(s.getBytes("ISO-8859-1"), ProjectUtil.ENCODE);
                } catch (UnsupportedEncodingException ex) {
                    //Logger.getLogger(Util.class.getName()).log(Level.SEVERE, null, ex);
                    logger.error("转码异常:input = " + s + "; ex = " + ex.toString());
                }
            }
        }
        logger.info("转码 input = " + s);
        return s;

    }

    /**
     * 获取远程地址的返回代码
     * @param url 远程地址，例如http://pay.mapbar.com/index.html
     * @param map 提交的参数
     * @return  返回值,当失败是返回null
     */
    public static String getSrc(String url, Map<String, String> map) {

        if (url == null || map == null) {
            return null;

        }
        //设置代理
        DefaultHttpClient httpclient = new DefaultHttpClient();

        httpclient.getParams().setIntParameter(HttpConnectionParams.SO_TIMEOUT, 5000); //超时设置
        httpclient.getParams().setIntParameter(HttpConnectionParams.CONNECTION_TIMEOUT, 5000);//连接超时

        HttpPost httpPost = new HttpPost(url);

        //添加参数
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        Iterator it = map.keySet().iterator();
        if (it != null) {

            Object key = null;
            while (it.hasNext()) {
                key = it.next();
                if (key != null) {
                    nvps.add(new BasicNameValuePair(key.toString(), map.get(key.toString())));
                    logger.info("添加参数：" + key.toString() + "=" + map.get(key.toString()));
                }
                key = null;
            }
        }
        it = null;

        try {
            httpPost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
        } catch (Exception ex) {
            logger.error("Util#httpost.setEntity(new UrlEncodedFormEntity(nvps, ProjectUtil.ENCODE)); " + ex.toString());
        }

        logger.info("请求地址：" + httpPost.getURI());
        HttpResponse response = null;
        try {
            response = httpclient.execute(httpPost);
        } catch (IOException ex) {
            logger.error("Util#httpclient.execute(httpost) " + ex.toString());
            //ex.printStackTrace();
        } catch (Exception ex) {
            logger.error("Util#httpclient.execute(httpost) " + ex.toString());
            //ex.printStackTrace();
        }


        if (response == null) {
            logger.error("获取接口数据异常");
            return null;
        } else {
            logger.info(response.getStatusLine() + "," + httpPost.getURI());
        }

        //获取代码
        HttpEntity entity = null;
        try {
            entity = response.getEntity();
            if (entity != null) {
                return EntityUtils.toString(entity, ProjectUtil.ENCODE);
                //System.out.println(sb);
            }
        } catch (Exception e) {
            logger.error("获取接口返回值异常：" + e.toString());
        } finally {
            //关闭
            try {
                httpclient.getConnectionManager().shutdown();

            } catch (Exception e) {
                logger.error("关闭httpclient异常" + e.toString());
            }
            httpclient = null;
            httpPost = null;
            response = null;
            entity = null;

        }

        return null;

    }

    /**
     * 获取接口配置文件
     */
    public static String getUrl(String key) {

        if (key != null) {
            logger.info("获取接口url地址成功:[" + key + "=" + urlPros.getProperty(key) + "]");
            return urlPros.getProperty(key);
        } else {
            logger.error("获取接口url地址失败:[" + key + "]");
            return null;

        }
    }

    public static void initUrlPros(Properties p) {
        if (p == null) {
            logger.error("初始化接口配置url文件失败，程序将无法正常运行");
        } else {
            urlPros = p;
            logger.info("初始化接口url配置文件成功");
            p.list(System.out);
        }

    }

    /**
     * 通过cookie获取用户信息
     * @param cookies
     * @return 返回一个用户实例，存储用户信息
     */
    public static User getUserInfoFromCookie(Cookie cookies[]) {

        if (cookies == null) {
            return null;
        } else {
            User user = new User();
            for (Cookie c : cookies) {

                if (c.getName() == null || c.getValue() == null) {
                    continue;
                }

                if (ProjectUtil.USER_NAME_IN_COOKIE.equals(c.getName())) {
                    user.setUserName(c.getValue().replaceAll("%25", "%"));
                } else if (ProjectUtil.USER_ID_IN_COOKIE.equals(c.getName())) {
                    if (c.getValue() != null && !"".equals(c.getValue().trim())) {
                        try {
                            user.setUserId(Integer.parseInt(c.getValue().trim()));
                        } catch (Exception e) {
                            logger.error(e.toString());
                        }

                    }
                } else if (ProjectUtil.USER_IDC_IN_COOKIE.equals(c.getName())) {
                    user.setUserIdc(c.getValue().replaceAll("%25", "%"));
                }
            }
            logger.info("从cookie中获取用户信息：" + user.toString());

            return user;
        }

    }

    public static JSONObject initJSONObject(String s) {

        if (s == null) {
            return null;
        } else {
            return JSONObject.fromObject(s);
        }
    }

    /**
     * 向cookie添加内容
     * @param key
     * @param value
     */
    public static void addCookie(String key, String value) {

        if (key == null || value == null) {
            return;
        }
        try {
            Cookie cookie = new Cookie(key, value);
            cookie.setPath("/");
            cookie.setDomain("mapbar.com");
            cookie.setMaxAge(24*3600*1000);
            ServletActionContext.getResponse().addCookie(cookie);
            logger.info("添加cookie：[key=" + key + ",value=" + value + "]");
        } catch (Exception e) {
            logger.error("添加cookie错误：[key=" + key + ",value=" + value + "]" + e.toString());
        }

    }

    /**
     * 从cookie取值
     * @param key
     */
    public static String getValueFromCookie(String key) {

        if (key == null || "".equals(key)) {
            return "";
        }
        try {

            Cookie cookies[] = ServletActionContext.getRequest().getCookies();
            if (cookies != null) {
                for (Cookie c : cookies) {
                    if (key.equals(c.getName())) {
                        return c.getValue();
                    }
                }
            }
            logger.info("获取cookie[key=" + key + "]");

        } catch (Exception e) {
            logger.error("获取cookie错误：[key=" + key + "]" + e.toString());
        }
        return "";

    }

    public static boolean addLogonCookie(User user, String store , HttpServletResponse response) {
        if(user == null || response == null){
            return false;
        }

        int expiry =24*3600;
        if(store != null && !"default".equals(store)){
            try {
                expiry = Integer.parseInt(store) * expiry;
            } catch (Exception e) {
                logger.error(e.toString());
            }

        }
        
        //写cookie
        //HttpServletResponse response = ServletActionContext.getResponse();

         Cookie cookie = null;
        //userName
        cookie = null;
        cookie = new Cookie(ProjectUtil.USER_NAME_IN_COOKIE, user.getUserName());
        cookie.setPath("/");
        cookie.setDomain("mapbar.com");
        cookie.setMaxAge(expiry);
        
        response.addCookie(cookie);

        //userId
        cookie = null;
        cookie = new Cookie(ProjectUtil.USER_ID_IN_COOKIE, user.getUserId() + "");
        cookie.setPath("/");
        cookie.setDomain("mapbar.com");
        cookie.setMaxAge(expiry);

        response.addCookie(cookie);

        //userIdc
        cookie = null;
        cookie = new Cookie(ProjectUtil.USER_IDC_IN_COOKIE, user.getUserIdc());
        cookie.setPath("/");
        cookie.setDomain("mapbar.com");
        cookie.setMaxAge(expiry);

        response.addCookie(cookie);

        //response = null;
        cookie = null;
        logger.info("用户"+user +"写cookie,expiry="+expiry);
        return true;
    }

    public static void main(String s[]) {

        Map<String, String> map = new HashMap<String, String>();
        map.put("name", "hitman3");
        map.put("pass", "321321");
        logger.info(getSrc("http://hi.mapbar.com/mapjson/userlogin.jsp", map));
        //JSONObject json = JSONObject.fromObject("{key:'111111'}");
        //System.out.println(json.getString(("key")));
        //org/apache/commons/collections/map/ListOrderedMap
    }
}
